#include "unary.h"
#include <QDebug>
#include <fstream>
std::string GreeterClient::SayHello(const std::string &user)
{
    // Data we are sending to the server.
    HelloRequest request;
    request.set_name(user);

    // Container for the data we expect from the server.
    HelloReply reply;

    // Context for the client. It could be used to convey extra information to
    // the server and/or tweak certain RPC behaviors.
    ClientContext context;

    // The actual RPC.
    Status status = stub_->SayHello(&context, request, &reply);

    // Act upon its status.
    if (status.ok()) {
        return reply.message();
    } else {
        qDebug() << status.error_code() << ": " << status.error_message().c_str();
        return "RPC failed";
    }
}


void GreeterAsynClient::SayHello(const std::string &user)
{
    // Data we are sending to the server.
    HelloRequest request;
    request.set_name(user);

    // Call object to store rpc data
    AsyncClientCall* call = new AsyncClientCall;

    // stub_->PrepareAsyncSayHello() creates an RPC object, returning
    // an instance to store in "call" but does not actually start the RPC
    // Because we are using the asynchronous API, we need to hold on to
    // the "call" instance in order to get updates on the ongoing RPC.
    call->response_reader =
        stub_->PrepareAsyncSayHello(&call->context, request, &cq_);

    // StartCall initiates the RPC call
    call->response_reader->StartCall();

    // Request that, upon completion of the RPC, "reply" be updated with the
    // server's response; "status" with the indication of whether the operation
    // was successful. Tag the request with the memory address of the call object.
    call->response_reader->Finish(&call->reply, &call->status, (void*)call);

}

void GreeterAsynClient::AsyncCompleteRpc()
{
    void* got_tag;
    bool ok = false;

    // Block until the next result is available in the completion queue "cq".
    while (cq_.Next(&got_tag, &ok)) {
        // The tag in this example is the memory location of the call object
        AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);

        // Verify that the request was completed successfully. Note that "ok"
        // corresponds solely to the request for updates introduced by Finish().
        GPR_ASSERT(ok);

        if (call->status.ok())
            qDebug() << "Greeter received: " << call->reply.message().c_str() ;
        else
            std::cout << "RPC failed" << std::endl;

        // Once we're complete, deallocate the call object.
        delete call;
    }
}

std::string ReadFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("Unable to open file: " + filename);
    }
    return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}

void GreeterClientTest()
{
      // 创建一个使用 HTTPS 的 gRPC 通道

        // 配置 SSL 证书
        grpc::SslCredentialsOptions ssl_opts;

        // 默认情况下，.NET Core 使用的自签名证书一般是由 .NET Core 的开发证书生成的
        // 在实际应用中，你需要将这些证书信息存储在 PEM 文件中
        ssl_opts.pem_root_certs = ReadFile("certificate.crt"); // CA 根证书

        auto creds = grpc::SslCredentials(ssl_opts);


        // 创建 SSL 凭据
        auto credentials = grpc::SslCredentials(ssl_opts);
        GreeterClient greeter(grpc::CreateChannel(
        "localhost:6001", credentials));

//        GreeterClient greeter(grpc::CreateChannel(
//            "localhost:6001", grpc::InsecureChannelCredentials()));
        std::string user("world");
        std::string reply = greeter.SayHello(user);
        qDebug() << "Greeter received: " << reply.c_str();

}

void GreeterAsynClientTest()
{

    GreeterAsynClient greeter(grpc::CreateChannel(
        "localhost:50051", grpc::InsecureChannelCredentials()));

    // Spawn reader thread that loops indefinitely
    std::thread thread_ = std::thread(&GreeterAsynClient::AsyncCompleteRpc, &greeter);

    for (int i = 0; i < 100; i++) {
    std::string user("world " + std::to_string(i));
    greeter.SayHello(user);  // The actual RPC call!
    }

    qDebug() << "Press control-c to quit" ;
    thread_.join();  //blocks forever

}
